<template>
  <div class="register-container">
    <!-- 注册表单 -->
    <el-form ref="registerForm" class="register-form"
             :model="registerForm" :rules="registerRules"
             auto-complete="on" label-position="left">
      <!-- 注册页面标题 -->
      <div class="title-container">
        <h3 class="title">注 册</h3>
      </div>

      <!-- 头像 -->
      <el-tooltip class="item" effect="dark" content="点击切换" placement="right">
        <el-form-item prop="avatar" class="register-avatar" >
          <el-image  ref="avatar"
                     :src="registerForm.avatar"
                     alt="头像"
                     @click.native="changeAvatar"
                     fit="cover">
          </el-image>
        </el-form-item>
      </el-tooltip>

      <!-- 用户名输入 -->
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user"/>
        </span>
        <el-input
          ref="username"
          v-model="registerForm.username"
          placeholder="用户名 （1-8个中英文或数字）"
          :maxlength="8"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <!-- id输入 -->
      <el-form-item prop="userid">
        <span class="svg-container">
          <svg-icon icon-class="userid"/>
        </span>
        <el-input
          ref="userid"
          v-model="registerForm.userid"
          placeholder="账号 （5-11个数字 不能以0开头）"
          name="userid"
          type="text"
          :maxlength="11"
          tabindex="2"
          auto-complete="on"
        />
      </el-form-item>

      <!-- 密码输入 -->
      <el-form-item prop="password">
        <!-- 输入框图标 -->
        <span class="svg-container">
          <svg-icon icon-class="password"/>
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="registerForm.password"
          :type="passwordType"
          placeholder="密码 （6-15个大小写字母或数字）"
          name="password"
          tabindex="3"
          auto-complete="on"
        />
        <!-- 密码是否可见 -->
        <span class="show-pwd" @click="showPwd('password','passwordType')">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"/>
        </span>
      </el-form-item>

      <!-- 确认密码输入 -->
      <el-form-item prop="confirmPass">
        <!-- 输入框图标 -->
        <span class="svg-container">
          <svg-icon icon-class="password"/>
        </span>
        <el-input
          :key="confirmPassType"
          ref="confirmPass"
          v-model="registerForm.confirmPass"
          :type="confirmPassType"
          placeholder="确认密码 （两次密码要保持一致）"
          name="confirmPass"
          tabindex="4"
          auto-complete="on"
        />
        <!-- 密码是否可见 -->
        <span class="show-pwd" @click="showPwd('confirmPass','confirmPassType')">
          <svg-icon :icon-class="confirmPassType === 'password' ? 'eye' : 'eye-open'"/>
        </span>
      </el-form-item>

      <!-- 注册按钮 -->
      <el-button :loading="loading" type="primary"
                 style="width:100%;margin-bottom:30px;"
                 @click.native.prevent="handleRegister">注册
      </el-button>
      <div class="to-login">
        <router-link to="/login">已有账号？去登录</router-link>
      </div>
      <el-checkbox true-label="ONLINE"
                   false-label="OFFLINE"
                   v-model="registerForm.status">注册完成后自动登录</el-checkbox>
    </el-form>
  </div>
</template>

<script>
  import {validUsername,validUserid,validUserPass,validUserIdUnique} from '@/utils/validate';
  import {getDefaultAvatars,idUnique} from "@/api/user";


  export default {
    name: "index",
    data() {
      // 校验用户名
      const validateUsername = (rule, value, callback) => {
        if (!validUsername(value)) {
          callback(new Error('请输入合法名称 （1-8个中英文或数字）'))
        } else {
          callback()
        }
      }
      // 校验账号
      const validateUserid =async (rule,value,callback)=>{
        if (!validUserid(value)) {
          callback(new Error('请输入合法账号 （5-11个数字 不能以0开头）'));
        } else {
          // 校验账号是否已经存在
          await idUnique(value).then(res=>{
            if(res.content.result){
              callback();
            }else {
              callback(new Error("该账号已存在，换个账号试试吧！"))
            }
          })
        }
      }
      // 校验第一个密码
      const validatePassword = (rule, value, callback) => {
        if (!validUserPass(value)) {
          callback(new Error('密码由 6-15个大小写字母或数字组成'))
        } else {
          this.$refs.registerForm.validateField('confirmPass')
          callback()
        }
      }
      // 校验第二个密码
      const validateConfirmPass = (rule,value,callback)=>{
        if(this.registerForm.password !== value){
          callback(new Error("两次密码输入不一致"))
        }else{
          callback()
        }
      }
      return {
        // 用户注册信息
        registerForm: {
          avatar:'',
          username: '',
          userid: '',
          password: '',
          confirmPass: '',
          status:'ONLINE'
        },
        // 用户注册校验规则
        registerRules:{
          username: [{ required: true, trigger: 'blur', validator: validateUsername }],
          userid: [{required:true,trigger:'blur',validator:validateUserid}],
          password: [{ required: true, trigger: 'blur', validator: validatePassword }],
          confirmPass: [{required:true,trigger:'blur',validator:validateConfirmPass}]
        },
        passwordType: 'password',
        confirmPassType: 'password',
        loading:false,
        // 候选头像列表
        avatars:[],
        avatarIndex:0,
      }
    },
    mounted() {
      // 请求默认头像列表
      getDefaultAvatars().then(res=>{
        this.avatars = res.content.avatars
        this.registerForm.avatar = this.avatars[this.avatarIndex]
      })
    },
    methods: {
      // 输入框输入的密码是否可见
      showPwd(element,type) {
        if (this[type] === 'password') {
          this[type] = ''
        } else {
          // 修改数据
          this[type] = 'password'
        }
        // dom还没有更新
        this.$nextTick(() => {
          // Dom现在更新了
          this.$refs[element].focus()
        })
      },
      // 注册按钮绑定事件
      handleRegister() {
        // 校验整个表单
        this.$refs.registerForm.validate(valid=>{
          if(valid){
            this.loading = true
            console.log(this.registerForm)
            this.$store.dispatch('user/signUp',this.registerForm).then(()=>{
              if(this.registerForm.status === 'ONLINE'){
                this.$router.push('/')
                this.loading = false
              }
            }).catch(err=>{
              console.log(err)
              this.loading = false
            })
          }else{
            return false
          }
        })
      },
      // 切换头像
      changeAvatar(){
        this.avatarIndex+=1;
        if(this.avatarIndex === this.avatars.length){
          this.avatarIndex = 0;
        }
        this.registerForm.avatar = this.avatars[this.avatarIndex]
      }
    }
  }
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg: #283443;
  $light_gray: #fff;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .register-container .el-input input {
      color: $cursor;
    }
  }

  /* reset element-ui css */
  .register-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #eee;

  .register-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;

    .register-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }


    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 30px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
  }
  .to-login {
    float: right;
    font-size: 14px;
    color: $light_gray;
  }
  .to-login:hover{
    color: #20a0ff;
  }
  .register-avatar {
    margin: 20px auto;
  }
  .register-avatar, .el-image{
    width: 100px;
    height: 100px;
  }
</style>
